import React, { useEffect, useState } from 'react';
import type { ReactElement } from 'react';
import { cloneDeep } from 'lodash';
import styles from './index.less';
import moment from 'moment';
import { DatePicker, Spin } from 'antd';
import { LeftOutlined, RightOutlined } from '#/utils/antdIcons.js';
import { initValue, getDate } from '../../tool';
import { WEEK_DAY, TYPEDATA, TYPE_ARR } from '../../dictionary';
import type { IDateData, ICalenderOption } from '../../type';

interface IProps {
  /**
   * 选项
   */
  options: ICalenderOption;
  /**
   * 切换月份
   */
  setMonthViewParams: (params: { beginDate: string; endDate: string }) => void;
  /**
   * 搜索
   */
  setSearchCriteriaData: (params: any) => any;

  /**
   * 是否在加载中
   */
  isLoading: boolean;
  /**
   * 更新组件
   */
  setSelectFlashKey?: any;
  /**
   * 更新源数据
   */
  checkedFlashKey?: number;
  /**
   * 更新月份
   */
  setCheckedDate?: any;
  /**
   * 月份
   */
  checkedDate: any;
}

const Calender = ({
  setCheckedDate,
  checkedDate,
  options,
  setSelectFlashKey,
  checkedFlashKey,
  setMonthViewParams,
  setSearchCriteriaData,
  isLoading,
}: IProps): ReactElement => {
  const [dateData, setDateData] = useState<IDateData[]>([]);

  const [nowMonthData, setNowMonthData] = useState<string[]>([]);

  useEffect(() => {
    if (checkedFlashKey) {
      const obj = getDate(checkedDate);
      setDateData(obj?.monthData || []);
      setNowMonthData(obj?.nowMonthData || []);
    }
  }, [checkedFlashKey]);

  useEffect(() => {
    const obj = getDate(checkedDate);
    setDateData(obj?.monthData || []);
    setNowMonthData(obj?.nowMonthData || []);
    setSearchCriteriaData({ dateList: obj?.dateList || [] });
  }, [checkedDate]);

  // 上一个月
  const handelMinus = () => {
    const date = moment(checkedDate).subtract(1, 'month').startOf('month').format('YYYY-MM-DD');
    const params = {
      beginDate: moment(checkedDate).subtract(1, 'month').startOf('month').format('YYYY-MM-DD'),
      endDate: moment(checkedDate).subtract(1, 'month').endOf('month').format('YYYY-MM-DD'),
    };
    setCheckedDate(date);
    setMonthViewParams(params);
    setSelectFlashKey(moment().valueOf());
  };

  // 下一个月
  const handelAdd = () => {
    const date = moment(checkedDate).add(1, 'month').startOf('month').format('YYYY-MM-DD');
    const params = {
      beginDate: moment(checkedDate).add(1, 'month').startOf('month').format('YYYY-MM-DD'),
      endDate: moment(checkedDate).add(1, 'month').endOf('month').format('YYYY-MM-DD'),
    };
    if (moment(date).format('YYYY-HH') !== moment().format('YYYY-MM')) {
      setCheckedDate(date);
      setMonthViewParams(params);
    }
    setSelectFlashKey(moment().valueOf());
  };

  // 切换月份
  const handelDate = (date: any) => {
    const _date = moment(date).startOf('month').format('YYYY-MM-DD');
    setCheckedDate(_date);
    const params = {
      beginDate: moment(date).startOf('month').format('YYYY-MM-DD'),
      endDate: moment(date).endOf('month').format('YYYY-MM-DD'),
    };
    setMonthViewParams(params);
    setSelectFlashKey(moment().valueOf());
  };

  // 选择日期
  const handelCalender = (value?: string) => {
    const list = dateData.map((item: IDateData) => {
      return {
        ...item,
        isChecked: value == item.value ? !item.isChecked : item.isChecked,
      };
    });
    const data = list
      ?.filter((item: IDateData) => {
        return item.isChecked;
      })
      ?.map((item) => {
        return item.value;
      });
    let arr = cloneDeep(data);
    if (data.length === 0) {
      arr = cloneDeep(nowMonthData);
    }
    setDateData(list);
    setSearchCriteriaData({ dateList: arr });
  };

  const itemRender = (item: IDateData) => {
    const dateObj: any = options?.[moment(item?.value || '').format('YYYY-MM-DD')] || {};
    return TYPE_ARR.map((i: string) =>
      dateObj[i] ? (
        <span
          className={`${styles.littleCircle} ${
            i === 'notice'
              ? styles.noriceCircle
              : i === 'todo'
              ? styles.todoCircle
              : styles.sequenceCircle
          } `}
          style={{ background: TYPEDATA[i].color }}
          key={i}
        />
      ) : null,
    );
  };

  const renderCalender = () => {
    return dateData.map((item: IDateData) => {
      return item.isShow ? (
        <div className={styles.calenderItem} key={item.value}>
          <div
            className={item.isChecked ? styles.chekedContent : styles.content}
            onClick={() => {
              handelCalender(item?.value);
            }}
          >
            <div className={item.isChecked ? styles.chekedLine : styles.line} />
            <div className={styles.info}>
              <div className={item.isChecked ? styles.chekedValue : styles.value}>
                {initValue(item?.value || '')}
              </div>
              <div className={styles.circleCalenders}>{itemRender(item) || ''}</div>
            </div>
          </div>
        </div>
      ) : (
        <div className={styles.unShow} key={item.value} />
      );
    });
  };

  return (
    <div className={styles.container}>
      <div className={styles.top}>
        <div className={styles.minus} onClick={() => handelMinus()}>
          <LeftOutlined className={styles.logo} />
        </div>
        <div className={styles.topTime}>
          <DatePicker
            picker="month"
            value={moment(checkedDate)}
            format={'YYYY年MM月'}
            onChange={handelDate}
            allowClear={false}
          />
        </div>
        <div className={styles.add} onClick={() => handelAdd()}>
          <RightOutlined className={styles.logo} />
        </div>
      </div>
      <div className={styles.bottom}>
        <div className={styles.bottomTop}>
          {WEEK_DAY?.map((item) => (
            <div className={styles.item} key={item}>
              {item}
            </div>
          ))}
        </div>
        <Spin spinning={isLoading}>
          <div className={styles.bottomMain}>{renderCalender()}</div>
        </Spin>
        <div className={styles.result}>
          {Object.values(TYPEDATA).map((item: any) => (
            <div key={item.type}>
              <span style={{ background: item?.color }} className={styles.circle} />
              {item?.title || ''}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};
export default Calender;
